<template>
	<div class="page-container">
		<el-card class="page-card w-full pref">
			<div class="flex justify-between w-full flex-wrap">
				<div class="md:w-[376px] md:mr-[32px] <sm:mb-[20px] pref__left">
					<div class="flex items-center mb-[24px] mt-[24px]">
						<el-input v-model="searchName" class="!h-[36px] mr-[12px] text-[12px]" clearable placeholder="请输入专区名称" maxlength="10" show-word-limit @change="getZoneList"> </el-input>
						<el-button type="primary" class="!h-[36px] !w-[100px]" icon="el-icon-plus" @click="showAddPrefecture">新增 </el-button>
					</div>
					<el-table ref="table" stripe :data="zoneList" highlight-current-row :height="632" @row-click="setPrefecture">
						<el-table-column :formatter="emptyToString" align="center" label="序号" prop="index" width="70">
							<template slot-scope="scope">
								{{ scope.$index + 1 }}
							</template>
						</el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="专区名称" prop="zoneName" min-width="90" />
						<el-table-column :formatter="emptyToString" align="center" label="专区图片" prop="zonePicture" min-width="90">
							<template slot-scope="scope">
								<div class="h-full flex items-center justify-center">
									<el-image style="width: 48px; height: 48px" :src="scope.row.zonePicture" :preview-src-list="[scope.row.zonePicture]"></el-image>
								</div>
							</template>
						</el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="操作" width="120">
							<template slot-scope="scope">
								<div class="flex items-center justify-center">
									<el-button class="!p-0 text-[14px]" type="text" @click.stop="showEditPrefecture(scope.row.id)">修改 </el-button>
									<el-divider direction="vertical"></el-divider>
									<el-button v-hasPermi="['mall:category:remove']" class="!p-0 !text-[#F14A46] text-[14px]" type="text" @click.stop="delEditPrefecture(scope.row.id)">删除 </el-button>
								</div>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<el-card shadow="never" class="pref__right md:flex-1 !<sm:border-none !<sm:pl-0" :body-style="{ padding: '0 !important' }">
					<div class="pt-[24px]">
						<el-form slot="header" ref="queryParam" :inline="true" :model="queryParams" label-width="100px">
							<el-form-item label="商品ID:" prop="goodsId">
								<el-input v-model.trim="queryParams.goodsId" placeholder="请输入商品ID" maxlength="6" show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="商品名称:" prop="goodsName">
								<el-input v-model.trim="queryParams.goodsName" placeholder="请输入商品名称" maxlength="11" show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="供应商名称:" prop="userName">
								<el-input v-model.trim="queryParams.userName" placeholder="请输入供应商名称"></el-input>
							</el-form-item>
						</el-form>
					</div>
					<div class="page-card-options">
						<l-search @search="queryList" @refresh="resetQuery" />
						<el-button type="primary" icon="el-icon-plus" @click="showAddGoods">新增 </el-button>
					</div>
					<el-table :data="tableData" stripe :height="440" class="mb-[118px]" @sort-change="handleSortChange">
						<el-table-column :formatter="emptyToString" align="center" label="序号">
							<template slot-scope="scope">
								<span>{{ scope.row.sort + 1 }}</span>
							</template>
						</el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="商品ID" prop="goodsId"></el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="商品名称" prop="goodsName" show-overflow-tooltip>
							<template slot-scope="scope">
								<span style="color: #1a2483">{{ scope.row.goodsName }}</span>
							</template>
						</el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="商品图片" prop="picUrl">
							<template slot-scope="scope">
								<el-image :src="scope.row.picture" style="width: 48px; height: 48px"></el-image>
							</template>
						</el-table-column>
						<el-table-column :formatter="emptyToString" align="center" min-width="120" label="商品价格" prop="retailPrice" sortable></el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="供应商名称" prop="userName"></el-table-column>
						<el-table-column :formatter="emptyToString" align="center" label="展示顺序">
							<template slot-scope="scope">
								<el-button :circle="true" class="sortOrder" icon="el-icon-caret-top" size="mini" @click="reSortOrderReduce(scope.row.id, scope.row.zoneId)"></el-button>
								<el-button :circle="true" class="sortOrder" icon="el-icon-caret-bottom" size="mini" @click="reSortOrderPlus(scope.row.id, scope.row.zoneId)"></el-button>
							</template>
						</el-table-column>
						<el-table-column :formatter="emptyToString" align="center" fixed="right" label="操作" width="100">
							<template slot-scope="scope">
								<div class="table-action flex items-center justify-center">
									<el-button type="danger" @click="delGoods(scope.row.id)">删除 </el-button>
								</div>
							</template>
						</el-table-column>
					</el-table>
					<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
				</el-card>
			</div>
		</el-card>
		<l-dialog v-model="showAddPrefectureFlag" :title="text" width="497px" @close="handleClose" @formClose="handleClose" @formSubmit="addPrefecture">
			<el-form ref="prefectureForm" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="专区名称:" prop="name">
					<el-input v-model.trim="form.name" maxlength="10" show-word-limit placeholder="请输入专区名称"></el-input>
				</el-form-item>
				<el-form-item label="专区图片:" prop="zonePicture">
					<l-upload-image v-model="form.zonePicture" height="160px" width="160px" :limit="1" class="w-full">
						<div class="flex flex-col items-center">
							<svg-icon icon-class="add" size="29px" color="#CCCCCC" class="mb-[6px]"></svg-icon>
							<el-tooltip effect="dark" content="图片尺寸建议为 长160px, 宽160px， 支持图片类型jpj,png，图片大小不 超过4M" placement="top">
								<div class="text-[14px] text-[#cccccc] cursor-pointer">上传图片 <i class="el-icon-question"></i></div>
							</el-tooltip>
						</div>
					</l-upload-image>
				</el-form-item>
			</el-form>
		</l-dialog>
		<l-dialog v-model="addGoodsFlag" on-button-width="236px" close-button-width="236px" title="添加商品" width="1042px" @close="handleClose2" @formClose="handleClose2" @formSubmit="submit">
			<el-form ref="goodsForm" :model="goodsForm" inline label-width="100px">
				<el-form-item label="商品ID:" prop="id">
					<el-input v-model.trim="goodsForm.id" maxlength="6" show-word-limit class="!w-[240px] !max-w-[240px]" placeholder="请输入商品ID"></el-input>
				</el-form-item>
				<el-form-item label="商品名称:" prop="name">
					<el-input v-model.trim="goodsForm.name" maxlength="30" show-word-limit class="!w-[240px] !max-w-[240px]" placeholder="请选择商品名称"></el-input>
				</el-form-item>
				<el-form-item label="供应商名称:" prop="userName">
					<el-input v-model.trim="goodsForm.userName" maxlength="10" show-word-limit class="!w-[240px] !max-w-[240px]" placeholder="请选择供应商名称"></el-input>
				</el-form-item>
				<el-form-item label="商品价格:">
					<div class="flex items-center">
						<el-form-item prop="min">
							<el-input v-model="goodsForm.min" class="!w-[109px] !max-w-[109px]" placeholder="最低价"></el-input>
						</el-form-item>
						<span class="mr-[9px]">-</span>
						<el-form-item prop="max">
							<el-input v-model="goodsForm.max" class="!w-[109px] !max-w-[109px]" placeholder="最高价"></el-input>
						</el-form-item>
						<span class="text-[12px]">元</span>
					</div>
				</el-form-item>
				<el-form-item label="商品分类:" prop="cate">
					<el-cascader v-model="goodsForm.cate" class="el-input-240" :props="props" clearable expand-trigger="hover" placeholder="请选择分类" @change="handleCategoryChange" />
				</el-form-item>
				<el-form-item>
					<div class="page-modal-search">
						<el-button icon="el-icon-search" type="primary" @click="queryGoodsList">搜索 </el-button>
						<el-button icon="el-icon-refresh" @click="resetGoodsQuery">重置</el-button>
					</div>
				</el-form-item>
			</el-form>
			<div class="flex items-center text-[12px] mb-[10px]">
				已选择<span class="text-[#F14A46]">（{{ selectList.length }}）</span>个商品
			</div>
			<el-table ref="multipleTable" v-loading="goodsLoading" :data="goodsList" row-key="id" stripe @sort-change="handleGoodsSortChange" @selection-change="selectGoodsChange">
				<el-table-column :formatter="emptyToString" :reserve-selection="true" align="center" type="selection" width="55"> </el-table-column>
				<el-table-column :formatter="emptyToString" align="center" label="序号" type="index" width="55"> </el-table-column>
				<el-table-column :formatter="emptyToString" align="center" label="商品ID" prop="id" min-width="120"></el-table-column>
				<el-table-column :formatter="emptyToString" align="center" label="商品名称" prop="name" min-width="120" show-overflow-tooltip>
					<template slot-scope="scope">
						<span style="color: var(--primary-color)">{{ scope.row.name }}</span>
					</template>
				</el-table-column>
				<el-table-column :formatter="emptyToString" align="center" label="商品图片" prop="picUrl" min-width="120">
					<template slot-scope="scope">
						<el-image :src="scope.row.picUrl" style="width: 45px; height: 45px" :preview-src-list="[scope.row.picUrl]" :z-index="9999"></el-image>
					</template>
				</el-table-column>
				<el-table-column :formatter="emptyToString" align="center" label="商品分类" prop="oneLevel" min-width="120">
					<template slot-scope="scope">
						<div class="flex items-center">
							<span>{{ scope.row.oneLevel }}</span>
							<span> > </span>
							<span>{{ scope.row.twoLevel }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column :formatter="emptyToString" prop="userName" label="供应商名称" align="center" min-width="120"></el-table-column>
				<el-table-column :formatter="emptyToString" align="center" label="商品价格（元）" sortable prop="retailPrice" min-width="156"></el-table-column>
				<el-table-column :formatter="emptyToString" align="center" label="供应价格（元）" sortable prop="supplyPrice" min-width="156"></el-table-column>
			</el-table>
			<pagination class="!mb-[26px] !mt-[32px]" :limit.sync="goodsForm.pageSize" :page.sync="goodsForm.pageNum" :total="goodsTotal" @pagination="getGoodsList" />
		</l-dialog>
	</div>
</template>

<script>
import { listGoods } from '@/api/mall/goods';
import { listChild, listParent } from '@/api/mall/category';
import { addZone, addZoneGoods, delZone, delZoneGoods, editZone, editZoneGoods, getZoneGoodsList, getZoneInfo, getZoneList, sortOrderPlus, sortOrderReduce } from '@/api/mall/prefecture';
import debounce from 'lodash/debounce';
import tableMixins from '@/mixins/table';
import snakeCase from 'lodash/snakeCase';
export default {
	name: 'Prefecture',
	mixins: [tableMixins],
	data() {
		return {
			goodsLoading: false,
			zoneName: '', //专区名
			prefectureId: '', //专区id
			zoneList: [], //左侧图片
			text: '新增专区分类',
			searchName: '',
			showAddPrefectureFlag: false,
			queryParams: {
				pageNum: 1,
				pageSize: 6,
				goodsName: null,
				goodsId: null,
				sortStr: null,
				sortDesc: null,
				userName: null,
			},
			goodsForm: {
				pageNum: 1,
				pageSize: 5,
				name: null,
				cate: null,
				sortDesc: null,
				sortStr: null,
				id: null,
				userName: null,
				min: null,
				max: null,
			},
			imgList: [],
			total: 0,
			addGoodsFlag: false,
			form: {
				name: null,
				zonePicture: [],
			},
			rules: {
				sort: [
					{ required: true, message: '排序不能为空' },
					{ type: 'number', message: '排序必须为数字值' },
				],
				name: [{ required: true, message: '请输入专区名称', trigger: 'blur' }],
				zonePicture: [{ required: true, message: '请上传专区图片', trigger: 'blur' }],
			},
			tableData: [],
			props: {
				lazy: true,
				lazyLoad(node, resolve) {
					const { level, value } = node;
					if (level === 0) {
						listParent().then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: false,
							}));
							resolve(nodes);
						});
					} else {
						listChild(value).then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: true,
							}));
							resolve(nodes);
						});
					}
				},
			},
			goodsList: [],
			goodsTotal: 0,
			selectList: [],
			selectListNow: [],
		};
	},
	created() {
		this.getZoneList();
	},
	methods: {
		resetQuery() {
			this.$refs.queryParam.resetFields();
			this.queryList();
		},
		queryList() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		selectGoodsChange(value) {
			this.selectList = value;
		},
		resetGoodsQuery() {
			this.$refs.goodsForm.resetFields();
			this.queryGoodsList();
		},
		queryGoodsList() {
			this.goodsForm.pageNum = 1;
			this.getGoodsList();
		},
		handleGoodsSortChange(sort) {
			this.goodsForm.sortStr = snakeCase(sort.prop);
			this.goodsForm.sortDesc = sort.order;
			this.getGoodsList();
		},
		getGoodsList() {
			this.goodsLoading = true;
			listGoods(this.goodsForm)
				.then((response) => {
					this.goodsList = response.data.records;
					this.goodsTotal = response.data.total;
				})
				.finally(() => {
					this.goodsLoading = false;
				});
		},
		cancel() {},
		submit: debounce(
			function () {
				if (this.selectList.length < 1) {
					this.$message.error('请选择商品');
					return false;
				}
				let arr = [];
				for (let i = 0; i < this.selectList.length; i++) {
					this.selectList[i].zoneId = this.prefectureId;
					arr.push({
						zoneId: this.prefectureId,
						goodsName: this.selectList[i].name,
						goodsId: this.selectList[i].id,
						picture: this.selectList[i].picUrl,
					});
				}
				addZoneGoods(arr).then(() => {
					this.$message.success('添加成功!');
					this.selectListNow = this.selectList;
					this.selectList = [];
					this.getList();
					this.handleClose2();
				});
			},
			1500,
			{
				leading: true,
			}
		),
		getList() {
			if (!this.prefectureId) {
				this.$message.error('请先选择专区!');
				return;
			}
			this.queryParams.zoneId = this.prefectureId;

			getZoneGoodsList(this.queryParams).then((res) => {
				this.tableData = res.data.records;
				console.log(res.data);
				this.total = res.data.total;
			});
		},
		//点击图片事件
		setPrefecture(row, column, event) {
			for (let i = 0; i < this.zoneList.length; i++) {
				if (row.id == this.zoneList[i].id) {
					this.$set(this.zoneList[i], 'select', true);
				} else {
					this.$set(this.zoneList[i], 'select', false);
				}
			}
			this.$refs.queryParam.resetFields();
			this.prefectureId = row.id;
			this.zoneName = row.zoneName;

			this.getList();
		},
		getZoneList() {
			getZoneList({
				common: this.searchName,
			}).then((res) => {
				console.log(res);
				this.zoneList = res.data;
			});
		},
		delEditPrefecture(id) {
			this.$confirm('是否删除该专区', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				delZone({ id: [id] }).then(() => {
					this.$message({
						type: 'success',
						message: '删除成功!',
					});
					this.getZoneList();
				});
			});
		},
		delGoods(id) {
			this.$confirm('是否删除该商品?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				delZoneGoods({
					id: [id],
				}).then(() => {
					this.$message.success('删除商品成功!');
					this.getList();
				});
			});
		},
		editGoodsSort(id) {
			this.$prompt('商品显示排序', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /(^[1-9]\d*$)/,
				inputErrorMessage: '排序应为正整数',
			})
				.then(({ value }) => {
					editZoneGoods({
						zoneId: this.prefectureId,
						id,
						sort: value,
					}).then(() => {
						this.$message.success('编辑商品排序成功');
						this.getList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '取消输入',
					});
				});
		},
		queryGoods() {},

		handleCategoryChange(value) {
			this.goodsForm.category = value[value.length - 1];
		},
		handleClose2() {
			this.$refs.goodsForm.resetFields();
			if (this.$refs.multipleTable) {
				this.$refs.multipleTable.clearSelection();
			}
			this.selectList = [];
			this.addGoodsFlag = false;
		},
		showAddGoods() {
			if (!this.prefectureId) {
				this.$message.error('请先选择专区!');
				return;
			}
			this.getGoodsList();
			this.addGoodsFlag = true;
		},
		//
		handleClose() {
			this.$refs.prefectureForm.resetFields();
			this.showAddPrefectureFlag = false;
		},
		showEditPrefecture(id) {
			getZoneInfo({ id }).then((res) => {
				this.text = '编辑专区分类';
				this.showAddPrefectureFlag = true;
				this.$nextTick(() => {
					this.form = {
						name: res.data.zoneName,
						zonePicture: res.data.zonePicture,
						id,
					};
				});
			});
		},
		showAddPrefecture() {
			this.text = '新增专区分类';
			this.showAddPrefectureFlag = true;
		},
		addPrefecture: debounce(
			function () {
				this.$refs['prefectureForm'].validate((valid) => {
					if (valid) {
						let obj = {
							zoneName: this.form.name,
							zonePicture: this.form.zonePicture,
						};
						if (!this.form.id) {
							addZone(obj).then(() => {
								this.$message.success('新增成功');
								this.handleClose();
								this.getZoneList();
							});
						} else {
							obj.id = this.form.id;
							editZone(obj).then(() => {
								this.$message.success('编辑成功');
								this.handleClose();
								this.getZoneList();
							});
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			1500,
			{
				leading: true,
				trailing: false,
			}
		),
		reSortOrderReduce(id, zoneId) {
			sortOrderReduce({ id: id, zoneId: zoneId }).then(() => {
				this.getList();
				const { tree, treeNode, resolve } = this.maps.get(pid);
				this.$set(this.$refs.table.store.states.lazyTreeNodeMap, pid, []);
				this.load(tree, treeNode, resolve);
			});
		},
		reSortOrderPlus(id, zoneId) {
			sortOrderPlus({ id: id, zoneId: zoneId }).then(() => {
				this.getList();
			});
		},
	},
};
</script>
<style lang="scss" scoped>
.pref {
	&__left {
		::v-deep .el-input__inner {
			height: 36px;
			line-height: 36px;
		}
	}
	&__right {
		::v-deep .el-card__header {
			padding: 0 !important;
		}
		border: none;
		border-left: 1px solid #f3f4f7;
		padding-left: 32px;
	}
}
.bottom-btn-box {
	position: relative;
	display: flex;
	justify-content: center;
	padding-top: 20px;

	> div {
		position: absolute;
		font-size: 14px;
		height: 60px;
		line-height: 60px;
		left: 80px;

		span {
			color: #f14a46;
		}
	}

	.btn {
		margin-top: 10px;
		width: 136px;
		height: 40px;
		padding: 0;
		font-size: 18px;
	}

	.btn2 {
		background: #1a2483;
		border: none;
	}
}

.save-prefecture-btn {
	width: 333px;
	height: 44px;
	background: #1a2483;
	opacity: 1;
	padding: 0;
	border-radius: 4px;
	font-size: 18px;
	line-height: 44px;
	border: none;
	margin-top: 20px;
}
</style>
